<template>
  <el-dialog
    v-model="visible"
    title="分类管理"
    :width="dialogWidth"
    :before-close="handleClose"
    @close="handleClose"
    :class="{ 'mobile-dialog': isMobile }"
  >
    <div class="category-management">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="showAddCategoryModal = true" class="add-button">
          <el-icon><Plus /></el-icon>
          添加分类
        </el-button>
      </div>

      <!-- 分类列表 -->
      <el-row :gutter="24" class="categories-grid">
        <el-col :span="8" :sm="12" :md="8" :lg="6" v-for="category in categories" :key="category.id">
          <el-card class="category-card" shadow="hover">
            <div class="card-content">
              <div class="category-icon" :style="{ backgroundColor: category.color || '#007aff' }">
                <span v-if="category.icon">{{ category.icon }}</span>
                <el-icon v-else><Document /></el-icon>
              </div>
              <div class="category-info">
                <h3 class="category-name">{{ category.name }}</h3>
                <p class="category-meta" v-if="category.parent_name">父分类: {{ category.parent_name }}</p>
              </div>
              <div class="category-actions">
                <el-button size="small" @click="editCategory(category)" :icon="Edit" circle />
                <el-button size="small" type="danger" @click="deleteCategory(category)" :icon="Delete" circle />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="categories.length === 0" description="暂无分类">
        <el-button type="primary" @click="showAddCategoryModal = true">
          添加第一个分类
        </el-button>
      </el-empty>
    </div>

    <!-- 添加分类弹窗 -->
    <AddCategoryModal
      v-model:visible="showAddCategoryModal"
      :edit-data="editCategoryData"
      @close="handleCategoryModalClose"
      @success="handleCategorySuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useAccountingStore } from '@/stores/accounting';
import { Plus, Edit, Delete, Document } from '@element-plus/icons-vue';
import AddCategoryModal from './AddCategoryModal.vue';
import type { CategoryResponse } from '@/types/accounting';

interface Props {
  visible: boolean;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "close"): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const accountingStore = useAccountingStore();

// 响应式数据
const categories = ref<CategoryResponse[]>([]);
const showAddCategoryModal = ref(false);
const editCategoryData = ref<CategoryResponse | null>(null);

// 响应式布局
const isMobile = ref(false);
const dialogWidth = computed(() => isMobile.value ? '95%' : '80%');

// 检查屏幕尺寸
const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768;
};

onMounted(() => {
  checkScreenSize();
  window.addEventListener('resize', checkScreenSize);
});

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize);
});

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 获取分类列表
const fetchCategories = async () => {
  try {
    await accountingStore.fetchCategories();
    categories.value = accountingStore.categories;
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 编辑分类
const editCategory = (category: CategoryResponse) => {
  editCategoryData.value = category;
  showAddCategoryModal.value = true;
};

// 删除分类
const deleteCategory = async (category: CategoryResponse) => {
  if (!confirm('确定要删除这个分类吗？')) {
    return;
  }

  try {
    await accountingStore.deleteCategory(category.id);
    await fetchCategories();
  } catch (error) {
    console.error('删除分类失败:', error);
    alert('删除分类失败，请重试');
  }
};

// 处理分类成功
const handleCategorySuccess = async () => {
  editCategoryData.value = null;
  await fetchCategories();
  emit('success');
};

// 处理分类弹窗关闭
const handleCategoryModalClose = () => {
  editCategoryData.value = null;
  showAddCategoryModal.value = false;
};

// 处理弹窗关闭
const handleClose = () => {
  emit('close');
  emit('update:visible', false);
};

// 监听visible变化
watch(() => props.visible, async (newVisible) => {
  if (newVisible) {
    await fetchCategories();
  }
});
</script>

<style lang="scss" scoped>
.category-management {
  .toolbar {
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .add-button {
      border-radius: var(--el-border-radius-small);
      font-weight: 500;
      padding: 10px 20px;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: var(--el-box-shadow-light);
      }
    }
  }

  .categories-grid {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .category-card {
    transition: all 0.3s ease;
    height: 100%;
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color);
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: var(--el-box-shadow-light);
      border-color: var(--el-color-primary);
    }

    .card-content {
      display: flex;
      align-items: center;
      padding: 16px;
      gap: 16px;
    }
  }

  .category-icon {
    width: 56px;
    height: 56px;
    border-radius: var(--el-border-radius-base);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    flex-shrink: 0;
    font-size: 20px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.1);
    }
  }

  .category-info {
    flex: 1;
    min-width: 0;
  }

  .category-name {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0 0 8px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .category-meta {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .category-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.1);
      }
    }
  }
}

@media (max-width: 768px) {
  .categories-grid {
    .el-col {
      margin-bottom: 12px;
    }
  }
  
  .category-management {
    .toolbar {
      margin-bottom: 16px;
      
      .add-button {
        padding: 8px 16px;
        font-size: 13px;
      }
    }
  }
  
  :deep(.el-dialog) {
    margin: 0 !important;
    margin-top: 20px !important;
  }
}

@media (max-width: 480px) {
  .categories-grid {
    .el-col {
      margin-bottom: 8px;
    }
  }
  
  .category-card {
    .card-content {
      padding: 12px;
      gap: 12px;
    }
  }
  
  .category-icon {
    width: 48px;
    height: 48px;
    font-size: 18px;
  }
  
  .category-name {
    font-size: 14px;
  }
  
  .category-meta {
    font-size: 11px;
  }
}

// 移动端弹窗样式
:deep(.mobile-dialog) {
  .el-dialog {
    margin: 0 !important;
    margin-top: 10px !important;
    border-radius: var(--el-border-radius-small);
  }
  
  .el-dialog__body {
    padding: 16px;
  }
}
</style>